from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from utils.goods import get_categories,get_contents
class IndexView(View):
    def get(self,request):
        context = {
            'categories':get_categories(),
            'contents':get_contents()
        }

        return render(request,'index.html',context=context)


from apps.goods.models import SKU
class ListSKUView(View):
    def get(self,request,category_id):
        # 1. 接收参数
        query_params = request.GET
        # 2. 提取参数
        ordering = query_params.get('ordering','-createtime')
        page_size = query_params.get('page_size', 5)
        page = query_params.get('page',1)
        # 3. 验证参数
        # 4. 查询数据
        # 4.1 根据分类id查询数据
        # 4.2 查询的数据排序
        skus = SKU.objects.filter(category=category_id).order_by(ordering)
        # 4.3 查询的数据分页
        from django.core.paginator import Paginator
        # ① 创建分页类
        instance = Paginator(skus,page_size)
        # ② 获取指定页数的数据
        page_skus = instance.page(page)
        # ③ 获取总页数
        total = instance.num_pages

        # 将对象列表转换为字典
        data_list = []
        for item in page_skus.object_list:
            data_list.append({
                'id': item.id,
                'name': item.name,
                'price': item.price,
                'default_image_url': item.default_image.url    # 调用url 把图片 拼接 七牛云的外链

            })

        # 面包屑数据
        # 获取三级分类
        from apps.goods.models import GoodsCategory
        from utils.goods import get_breadcrumb
        category = GoodsCategory.objects.get(id=category_id)
        breadcrumb = get_breadcrumb(category)


        # 5. 返回响应
        return JsonResponse({
            'code':0,
            'errmsg': 'ok',
            'breadcrumb': breadcrumb,
            'list': data_list,
            'count': total
        })

class HotSKUView(View):
    def get(self,request,category_id):
        skus = SKU.objects.filter(category = category_id).order_by('-sales')[:2]
        # 将对象转换为字典
        data_list = []
        for item in skus:
            data_list.append({
                'id': item.id,
                'name': item.name,
                'price': item.price,
                'default_image_url': item.default_image.url
            })
        return JsonResponse({
            'code':'0',
            'errmsg':'OK',
            'hot_skus':data_list
        })


class DetailView(View):
    def get(self,request,sku_id):
        # 1. 根据sku_id查询sku数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code':'400','errmsg':'没有此商品'})
        # 2. 获取分类数据
        from utils.goods import get_categories
        categories = get_categories()
        # 3. 获取面包屑数据
        from utils.goods import get_breadcrumb
        breadcrumb = get_breadcrumb(sku.category)
        # 4. 获取规格和规格选项
        from utils.goods import get_goods_specs
        specs = get_goods_specs(sku)

        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': specs
        }

        return render(request,'detail.html',context=context)

from apps.goods.models import GoodsCategory,GoodsVisitCount
from datetime import date

class CategoryVisitView(View):
    def post(self,request,category_id):
        # 1. 根据分类id查询分类数据
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'分类信息错误'})
        # 2. 根据统计模型 查询当前的 分类记录 是否存在
        today = date.today()
        try:
            gvc = GoodsVisitCount.objects.get(category=category,date=today)
        except GoodsVisitCount.DoesNotExist:
            # 3. 如果不存在 则新增
            GoodsVisitCount.objects.create(
                category= category,
                count= 1,
                date= today
            )
        else:
            # 4. 如果存在,则访问量+1
            gvc.count += 1
            gvc.save()

        # 5. 返回响应
        return JsonResponse({'code':0, 'errmsg':'ok'})


from haystack.views import SearchView

class MeiduoSearchView(SearchView):
    def create_response(self):
        # haystack 会接受search中的请求 对接es
        context = self.get_context()
        #
        page = context.get('page')

        object_list = page.object_list
        #
        #
        data_list = []
        # 对对象列表进行遍历
        for item in object_list:
            data_list.append({
                'id':item.object.id,
                'name':item.object.name,
                'price':item.object.price,
                'default_image_url':item.object.default_image.url,
                "searchkey": context.get('query'),   # 搜索的关键字
                "page_size": context.get('paginator').num_pages,
                "count": context.get('paginator').count
            })

        return JsonResponse(data_list,safe=False)







